<?php
namespace avata;

/**
 * Undocumented class
 */
class Query {
    
    /**
     * 平台资源路径
     *
     * @var string
     */
    protected string $path;

    /**
     * 请求方式
     * 
     * GET | POST
     *
     * @var string
     */
    protected string $method;

    protected array $query;

    protected array $body;

    function __construct(array $query=[], array $body=[])
    {
        $this->query = $query;
        $this->body = $this->attachOperationId($body);
    }

    /**
     * 获得路径
     *
     * @return string
     */
    public function getPath(): string
    {
        return $this->path;
    }

    /**
     * 获得方法
     *
     * @return string
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    /**
     * 获得Body
     *
     * @return array
     */
    public function getBody(): array
    {
        return $this->body;
    }

    /**
     * Query参数格式化
     *
     * @return string
     */
    public function build(): string
    {
        return empty($this->query) 
            ? '' : '?' . http_build_query($this->query);
    }

    /**
     * 获取参数
     *
     * @return array
     */
    public function getParams(): array
    {
        $params = ['path_url' => $this->getPath()];
        
        foreach($this->query as $key => $value){
            $params["query_{$key}"] = strval($value);
        }

        foreach($this->body as $key => $value){
            $params["body_{$key}"] = $value;
        }

        if (!empty($params))
            $this->sortParams($params);

        return $params;
    }

    /**
     * 参数排序
     *
     * @param array $params
     * @return void
     */
    public function sortParams(array &$params): void
    {
        if (is_array($params)) {
            ksort($params);
        }

        foreach ($params as &$value){
            if (is_array($value)) {
                $this->sortParams($value);
            }
        }
    }

    /**
     * 时间
     *
     * @return float
     */
    public function time(): float
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)));
    }

    /**
     * 是否是操作
     *
     * @return boolean
     */
    public function isOperation(): bool
    {
        if(in_array($this->getMethod(), ['POST', 'PATCH', 'PUT', 'DELETE']))
            return true;
        
        return false;
    }

    /**
     * 生成操作ID
     *
     * @return string
     */
    public function generateOperationId(): string
    {
        return md5(microtime()) . md5(microtime());
    }

    /**
     * 附加操作ID
     *
     * @param array $item
     * @return array
     */
    public function attachOperationId(array $params): array
    {
        if($this->isOperation())
            $params['operation_id'] = $this->generateOperationId();

        return $params;
    }
}